package io;
import java.io.*;
import java.net.URL;
import java.net.HttpURLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtils {
    public void saveImage(String url, String savePath){
        try {
            ensureDirectoryExists(savePath);
            URL position = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) position.openConnection();
            File file = new File(savePath);
            try (InputStream inputStream = connection.getInputStream();
                 FileOutputStream outputStream = new FileOutputStream(file)) {
                byte[] buffer = new byte[8192];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }
            System.out.println("下载成功！\n");
            appendLog("Downloaded: " + url + " -> " + savePath);
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
    }
    public void ensureDirectoryExists(String dirPath){
        File file = new File(dirPath);
        File parentDir = file.getParentFile();
        if (parentDir != null) {
            parentDir.mkdirs();
        }
    }
    public static void appendLog(String log){
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String timestamp = dateFormat.format(new Date());
            String logEntry = timestamp + " " + log + "\n";
            try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("download_log.txt", true))) {
                bufferedWriter.write(logEntry);
            }
        } catch (IOException e) {
            System.err.println("写入日志失败: " + e.getMessage());
        }
    }
}
